package hero_info

import (
	"go_server/game_server/api/service/bag"
	"go_server/game_server/dataconfig/config_manager"
	"go_server/game_server/protocol/pb"
	"go_server/game_server/util"
	"go_server/zinx/ziface"
)

func (s *Hero_info_service) S2C_UnlockHero(conn ziface.IConnection, roleid int64, msg *pb.UnlockHeroC2S) pb.ErrorCodeManager {
	hero := Hero_info_serviceObj.LoadByRoleId(roleid)
	return on_S2C_UnlockHero(hero, conn, roleid, msg.Herocfgid, msg.Fragments)
}

func on_S2C_UnlockHero(hero *Cache_hero_info, conn ziface.IConnection, roleid int64, herocfgid int32, c2sfragments map[int32]int32) pb.ErrorCodeManager {
	if c2sfragments != nil {
		if hero.Contains(herocfgid) {
			return pb.ErrorCodeManager_HERO_INFO_EXISTS_HERO
		} else {
			if h1, ok1 := config_manager.GetStcTableHero_SheetHeroConfig(herocfgid); ok1 {
				legitems := util.NewSet[int32]()
				legitems.Add(h1.Unlockitemid) //专属碎片道具
				needcount := h1.UnlockNum     //需要数量

				/*				if crrencyfragments, ok := item.GetUpgradeItems(constants.Upgrade_HerocCrrencyFragments, h1.Quality); ok { //英雄通用碎片
								legitems.AddValue(crrencyfragments)
							}*/

				isAllOk := true
				useitems := make(map[int32]int32) //使用的道具
				for id, _ := range c2sfragments {
					isAllOk = isAllOk && legitems.Contains(id)
					useitems[id] = 0
				}
				if isAllOk {
					for id, count := range c2sfragments {
						for i := 0; i < int(count); i++ {
							if needcount > 0 {
								needcount--
								useitems[id]++
							} else {
								break
							}
						}

						if needcount <= 0 {
							break
						}
					}

					go bag.SubItemBatch(roleid, useitems)
					hcids := make([]int32, 1)
					hcids[0] = herocfgid
					_, code := Hero_info_serviceObj.S2C_AddHero(conn, roleid, hcids)
					return code
				} else {
					return pb.ErrorCodeManager_HERO_INFO_NOTLEG_UNLOCKHERO
				}
			} else {
				return pb.ErrorCodeManager_HERO_INFO_NOT_HEROCFGID
			}
		}
	} else {
		return pb.ErrorCodeManager_HERO_INFO_NOTENOUGH_UNLOCKHERO
	}
}
